#!/bin/bash
#
# @name:    fox - JiuWei Packages Management
# @repo:    https://gitee.com/TangYuanMaster/JiuWei
# @author:  TangYuanMaster
# @license: See the file 'LICENSE.txt'
#

set -e

# 初始化颜色
COLOR_DEFAULT="\e[0m"
COLOR_RED="\e[31m"
COLOR_GREEN="\e[32m"
COLOR_YELLOW="\e[33m"
COLOR_BLUE="\e[34m"
COLOR_PURPLE="\e[35m"
COLOR_CYAN="\e[36m"

#进程意外终止处理函数
interrupt_handler() {
    read -p "[*] Received Ctrl+C, Do you want to continue running the script? (Y/n)" answer
    case $answer in
        [Nn]) exit 1;;
        *) echo -e "${COLOR_GREEN}[*] Continuing...${COLOR_DEFAULT}" && return;;
    esac
}
trap interrupt_handler SIGINT

#ROOT环境检测 /Termux无需
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${COLOR_RED}[-] This command must be run as root!${COLOR_DEFAULT}"
        exit 1
    fi
}
if [ ! -n "$TERMUX_VERSION" ]; then
    check_root
fi

#检查变量$HOME
if [ ! -n "$HOME" ]; then
    echo -e "${COLOR_RED}[-] \$HOME variables do not exist, please set the variable \$HOME and try again.${COLOR_DEFAULT}"
fi

#声明变量
MAIN_DIR="$HOME/JiuWei"
INED_FILE=".installed" #记录所有已安装的包名（文本文件）
PACKAGES_INFO=".packages_info" #记录所有的包信息,方便search（文本文件）
PACKAGES_NAME=".packages_name" #记录所有的包名称,方便install（文本文件）
CONFIG_FILE="config.list" #配置文件（文本文件）
FOXINDEX_FILE=".foxindex" #放置FOXINDEX解压后产生的文件（文件夹）
CACHE_FILE=".cache" #放置从源中下载的安装包（文件夹）
BIN_FILE=".bin" #快捷命令存放（文件夹）
ST_FILE=".expand" #拓展状态文件
DEFAULT_ANSWER=Y

INED="$MAIN_DIR/$INED_FILE"
PACKAGES_INFO="$MAIN_DIR/$PACKAGES_INFO"
PACKAGES_NAME="$MAIN_DIR/$PACKAGES_NAME"
CACHE="$MAIN_DIR/$CACHE_FILE"
FOXINDEX="$MAIN_DIR/$FOXINDEX_FILE"
BIN="$MAIN_DIR/$BIN_FILE"
ST="$MAIN_DIR/$ST_FILE"
VERSION="0.6"
source "$MAIN_DIR/$CONFIG_FILE"
source_url="${SOURCE%/}"

#LOGO输出函数
logo() {
    if [ "$LOGO_PRINT" = "True" ];then
        echo -e "${COLOR_GREEN}          ______ _______   __"
        echo -e "${COLOR_GREEN}          |  ___|  _  \ \ / /"
        echo -e "${COLOR_GREEN}          | |_  | | | |\ V / "
        echo -e "${COLOR_GREEN}          |  _| | | | |/   \ "
        echo -e "${COLOR_GREEN}          | |   \ \_/ / /^\ \\"
        echo -e "${COLOR_GREEN}          \_|    \___/\/   \/"
        echo -e "${COLOR_BLUE}          ～ Version : $VERSION ～"
        echo -e "${COLOR_PURPLE}       JiuWei packages management${COLOR_DEFAULT}"
    fi
}

#HELP输出函数
usage() {
    echo -e "Usage: ${COLOR_YELLOW}fox [command] [package] [parameter]${COLOR_DEFAULT}"
    echo -e "${COLOR_GREEN}Commands:${COLOR_DEFAULT}"
    echo -e "  ${COLOR_CYAN}install${COLOR_DEFAULT}      - Install a package"
    echo -e "  ${COLOR_CYAN}remove${COLOR_DEFAULT}       - Remove a package"
    echo -e "  ${COLOR_CYAN}list${COLOR_DEFAULT}         - List all installed packages"
    echo -e "  ${COLOR_CYAN}search${COLOR_DEFAULT}       - Search for a package"
    echo -e "  ${COLOR_CYAN}upgrade${COLOR_DEFAULT}      - Upgrade installed packages"
    echo -e "  ${COLOR_CYAN}update${COLOR_DEFAULT}       - Update package index"
    echo -e "  ${COLOR_CYAN}info${COLOR_DEFAULT}         - Show package information"
    echo -e "  ${COLOR_CYAN}ABOUT${COLOR_DEFAULT}        - Show the info about JiuWei with fox"
    echo -e "${COLOR_GREEN}Parameters:${COLOR_DEFAULT}"
    echo -e "  ${COLOR_CYAN}--no-update${COLOR_DEFAULT}  - No update when run the commands"
    echo -e "  ${COLOR_CYAN}--debug${COLOR_DEFAULT}      - Display execution process"
}

#获取需要GitHub克隆的fox方案
get_from_github() {
    if ! wget -O "$CACHE/$package.fox" "$source_url/main/$package.fox"; then
        if [ -f "$ST" ]; then
            if ! wget -O "$CACHE/$package.fox" "$source_url/expand/$package.fox"; then
                echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the latest source is no longer supported ...${COLOR_DEFAULT}"
                exit 1
            fi
        else
            echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package need expand ...${COLOR_DEFAULT}"
            exit 1
        fi
    fi
}

#对fox方案进行读取
get_run() {
    if [[ "$1" == "install" ]]; then
        local num="1"
    elif [[ "$2" == "upgrade" ]]; then
        package_info=$(grep -A 5 "^P:$package$" "$FOXINDEX/FOXINDEX")
        status=$(echo "$package_info" | grep "^S:" | awk -F: '{print $2}' | tr -d '[:space:]')
        if [[ "$status" == "No" ]]; then
            echo -e "${COLOR_RED}[-] The project $package has stopped maintenance, stop updating !${COLOR_DEFAULT}"
            echo -e "${COLOR_BLUE}[*] If there is a false positive, please feed back me (see \"fox ABOUT\") .${COLOR_DEFAULT}"
            exit 1
        elif [[ "$status" == "Unkown" ]]; then
            read -p "[*] The project is suspected that it has stopped maintenance. Do you continue to execute updates? (Y/n)" answer
            case $answer in
                [Nn]) echo -e "${COLOR_BLUE}[*] If there is a false positive, please feed back me (see \"fox ABOUT\") .${COLOR_DEFAULT}" && echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
            esac
            echo -e "${COLOR_BLUE}[*] If there is a false positive, please feed back me (see \"fox ABOUT\") .${COLOR_DEFAULT}"
        fi
        local num="2"
    elif [[ "$2" == "remove" ]]; then
        local num="3"
    fi
    if grep -q "^R:$" "$CACHE/$package.fox"; then
        requirements=$(grep -A "$num" "^R:$" "$CACHE/$package.fox" | tail -n 1)
        IFS=',' read -ra req_array <<< "$requirements"
        for req in "${req_array[@]}"; do
            if ! grep -q "^${req}" "$INED"; then
                echo -e "${COLOR_BLUE}[*] Package '$req' has not been installed.Try \"fox install $req\"${COLOR_DEFAULT}"
                exit_code="1"
            fi
        done
        if [ "$req" -eq 1 ]; then
            exit 1
        fi
        exit_code="0"
    elif [ "$exit_code" -eq 0 ] || ! grep -q "^R:$" "$CACHE/$package.fox"; then
        if grep -q "^$sys_name/$sys_arch:$" "$CACHE/$package.fox"; then
            run=$(grep -A "$num" "^$sys_name/$sys_arch:$" "$CACHE/$package.fox" | tail -n 1)
        else
            if grep -q "^$SYSTEM_CATEGORY/$sys_arch:$" "$CACHE/$package.fox"; then
                run=$(grep -A "$num" "^$SYSTEM_CATEGORY/$sys_arch:$" "$CACHE/$package.fox" | tail -n 1)
            else
                if grep -q "^$sys_name:$" "$CACHE/$package.fox"; then
                    run=$(grep -A "$num" "^$sys_name:$" "$CACHE/$package.fox" | tail -n 1)
                else
                    if grep -q "^$sys_arch:$" "$CACHE/$package.fox"; then
                        run=$(grep -A "$num" "^$sys_arch:$" "$CACHE/$package.fox" | tail -n 1)
                    else
                        if grep -q "^generic:$" "$CACHE/$package.fox"; then
                            run=$(grep -A "$num" "^generic:$" "$CACHE/$package.fox" | tail -n 1)
                        else
                            echo -e "${COLOR_RED}[-] The tool does not support the current system architecture.${COLOR_DEFAULT}"
                            exit 1
                        fi
                    fi
                fi
            fi
        fi
    fi
}

#INSTALL部分函数
install_package() {
    if [ -s "$PACKAGES_NAME" ]; then
        pattern="$package:"
        if grep -q "^${pattern}" "$INED"; then
            echo -e "${COLOR_YELLOW}[*] Package '$package' is already installed.${COLOR_DEFAULT}"
        else
            if grep -qw "$package" "$PACKAGES_NAME"; then
                if [ "$GITEE_PRIORITY" = "True" ];then
                    if ! wget -O "$CACHE/$package.fox" "$source_url/main/Gitee/$package.fox"; then
                        if [ -f "$ST" ]; then
                            if ! wget -O "$CACHE/$package.fox" "$source_url/expand/Gitee/$package.fox"; then
                                echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee...${COLOR_DEFAULT}"
                                read -p "[*] Do you want to install fox file by default installation plan ? (y/N)" answer
                                case $answer in
                                    [Yy]) get_from_github;;
                                    *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                                esac
                            fi
                        else
                            echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee or need expand...${COLOR_DEFAULT}"
                            read -p "[*] Do you want to try for install fox file by default installation plan ? (y/N)" answer
                            case $answer in
                                [Yy]) get_from_github;;
                                *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                            esac
                        fi
                    fi
                else
                    get_from_github
                fi
            else
                echo -e "${COLOR_RED}[-] $package does not support installation, update the list of later lists? Try \"fox update\".${COLOR_DEFAULT}"
                exit 1
            fi
            get_run "install"
            update_run
            run="${run//\$MAIN_DIR/$MAIN_DIR}"
            run="${run//\$BIN/$BIN}"
            run="${run//\$PACKAGE_INSTALL/$PACKAGE_INSTALL}"
            run="${run//\$PACKAGE_UPGRADE/$PACKAGE_UPGRADE}"
            run="${run//\$PACKAGE_REMOVE/$PACKAGE_REMOVE}"
            if [[ "$run" == *"github.com"* ]]; then
                read -p "[*] Detected the need to retrieve files from GitHub. It is recommended to use a VPN. Press Enter to continue..."
            fi
            if [ "$parameters_1" = "--debug" ] || [ "$parameters_2" = "--debug" ]; then
                echo -e "${COLOR_BLUE}[*] $run${COLOR_DEFAULT}"
            fi
            eval "$run"
            
            if [ $? -eq 0 ]; then
                get_ver
                echo "$package:$version" >> "$INED"
                echo -e "${COLOR_GREEN}[+] Package '$package' has been installed.${COLOR_DEFAULT}"
            else
                echo -e "${COLOR_RED}[-] Failed to download package '$package'. Check your software source.${COLOR_DEFAULT}"
            fi
        fi
    else
        echo -e "${COLOR_RED}[-] Package_name text loss. Try \"fox update\".${COLOR_DEFAULT}"
    fi
}

#REMOVE部分函数
remove_package() {
    pattern="$package:"
    if grep -q "^${pattern}" "$INED"; then
        if [ ! -e "$CACHE/$package.fox" ]; then
            if [ "$GITEE_PRIORITY" = "True" ];then
                if ! wget -O "$CACHE/$package.fox" "$source_url/main/Gitee/$package.fox"; then
                    if [ -f "$ST" ]; then
                        if ! wget -O "$CACHE/$package.fox" "$source_url/expand/Gitee/$package.fox"; then
                            echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee...${COLOR_DEFAULT}"
                            read -p "[*] Do you want to install fox file by default installation plan ? (y/N)" answer
                            case $answer in
                                [Yy]) get_from_github;;
                                *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                            esac
                        fi
                    else
                        echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee or need expand...${COLOR_DEFAULT}"
                        read -p "[*] Do you want to try for install fox file by default installation plan ? (y/N)" answer
                        case $answer in
                            [Yy]) get_from_github;;
                            *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                        esac
                    fi
                fi
            else
                get_from_github
            fi
        fi
        get_run "remove"
        update_run
        run="${run//\$MAIN_DIR/$MAIN_DIR}"
        run="${run//\$BIN/$BIN}"
        run="${run//\$PACKAGE_INSTALL/$PACKAGE_INSTALL}"
        run="${run//\$PACKAGE_UPGRADE/$PACKAGE_UPGRADE}"
        run="${run//\$PACKAGE_REMOVE/$PACKAGE_REMOVE}"
        if [ "$parameters_1" = "--debug" ] || [ "$parameters_2" = "--debug" ]; then
            echo -e "${COLOR_BLUE}[*] $run${COLOR_DEFAULT}"
        fi
        eval "$run"
        sed -i "/^${pattern}$/d" "$INED"
        rm "$CACHE/$package.fox"
        echo -e "${COLOR_GREEN}[+] Package '$package' has been removed.${COLOR_DEFAULT}"
    else
        echo -e "${COLOR_YELLOW}[*] Package '$package' is not installed.${COLOR_DEFAULT}"
    fi
}

#LIST部分函数
list_packages() {
    if [[ -s "$INED" ]]; then
        echo -e "${COLOR_YELLOW}[*] Installed packages:${COLOR_DEFAULT}"
        cat "$INED"
    else
        echo -e "${COLOR_YELLOW}[*] No packages are currently installed.${COLOR_DEFAULT}"
    fi
}

#
generate_package_info() {
    awk -F ':' '/^P:/{print $2}' "$FOXINDEX/FOXINDEX" > "$PACKAGES_NAME"
    if [ -s "$PACKAGES_INFO" ]; then
        rm "$PACKAGES_INFO"
    fi
    while IFS= read -r package; do
        version=$(grep -A 4 "^P:$package$" "$FOXINDEX/FOXINDEX" | grep "^V:" | awk -F ':' '{print $2}')
        desc=$(grep -A 4 "^P:$package$" "$FOXINDEX/FOXINDEX" | grep "^T:" | awk -F ':' '{print $2}')
        echo "$package:$version | $desc" >> "$PACKAGES_INFO"
    done < "$PACKAGES_NAME"
}


search_package() {
    if [ -s "$PACKAGES_INFO" ]; then
        cat "$PACKAGES_INFO" | grep --color=auto "$package"
    else
        echo -e "${COLOR_RED}[-] Packages_info text loss. Try \"fox update\"${COLOR_DEFAULT}"
    fi
}

upgrade_a_package() {
    if [[ -s "$INED" ]]; then
        pattern="$package:"
        if grep -q "^${pattern}" "$INED"; then
            now_version=$(grep "^$package" "$INED" | awk -F: '{print $2}')
            
            package_info=$(grep -A 4 "^P:$package$" "$FOXINDEX/FOXINDEX")
            latest_version=$(echo "$package_info" | grep "^V:" | awk -F: '{print $2}' | tr -d '[:space:]')
            if (( $(echo "$latest_version > $now_version" | bc -l) )); then
                read -p "[*] Do you need to update data? (y/N)" answer
                case $answer in
                    [Yy]) update;;
                esac
                if [ ! -e "$CACHE/$package.fox" ]; then
                    if [ "$GITEE_PRIORITY" = "True" ];then
                        if ! wget -O "$CACHE/$package.fox" "$source_url/main/Gitee/$package.fox"; then
                            if [ -f "$ST" ]; then
                                if ! wget -O "$CACHE/$package.fox" "$source_url/expand/Gitee/$package.fox"; then
                                    echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee...${COLOR_DEFAULT}"
                                    read -p "[*] Do you want to install fox file by default installation plan ? (y/N)" answer
                                    case $answer in
                                        [Yy]) get_from_github;;
                                        *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                                    esac
                                fi
                            else
                                echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee or need expand...${COLOR_DEFAULT}"
                                read -p "[*] Do you want to try for install fox file by default installation plan ? (y/N)" answer
                                case $answer in
                                    [Yy]) get_from_github;;
                                    *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                                esac
                            fi
                        fi
                    fi
                else
                    get_from_github
                fi
            else
                echo -e "${COLOR_YELLOW}[*] Package '$package' already the latest version.${COLOR_DEFAULT}"
                exit 1
            fi
        else
            echo -e "${COLOR_YELLOW}[*] Package '$package' is not installed.${COLOR_DEFAULT}"
            exit 1
        fi
        get_run "upgrade"
        update_run
        run="${run//\$MAIN_DIR/$MAIN_DIR}"
        run="${run//\$BIN/$BIN}"
        run="${run//\$PACKAGE_INSTALL/$PACKAGE_INSTALL}"
        run="${run//\$PACKAGE_UPGRADE/$PACKAGE_UPGRADE}"
        run="${run//\$PACKAGE_REMOVE/$PACKAGE_REMOVE}"
        if [ "$parameters_1" = "--debug" ] || [ "$parameters_2" = "--debug" ]; then
            echo -e "${COLOR_BLUE}[*] $run${COLOR_DEFAULT}"
        fi
        eval "$run"
        echo -e "${COLOR_GREEN}[+] Package '$package' upgraded.${COLOR_DEFAULT}"
        update_now_version
    else
        echo -e "${COLOR_YELLOW}[*] No packages are currently installed.${COLOR_DEFAULT}"
    fi
}

upgrade_all_packages() {
    if [[ -s "$INED" ]]; then
        cat "$INED" | while IFS=':' read -r package _
        do
            now_version=$(grep "^$package" "$INED" | awk -F: '{print $2}')
            package_info=$(grep -A 4 "^P:$package$" "$FOXINDEX/FOXINDEX")
            latest_version=$(echo "$package_info" | grep "^V:" | awk -F: '{print $2}' | tr -d '[:space:]')
            if (( $(echo "$latest_version > $now_version" | bc -l) )); then
                read -p "[*] Do you need to update data? (y/N)" answer
                case $answer in
                    [Yy]) update;;
                esac
                if [ ! -e "$CACHE/$package.fox" ]; then
                    if [ "$GITEE_PRIORITY" = "True" ];then
                        if ! wget -O "$CACHE/$package.fox" "$source_url/main/Gitee/$package.fox"; then
                            if [ -f "$ST" ]; then
                                if ! wget -O "$CACHE/$package.fox" "$source_url/expand/Gitee/$package.fox"; then
                                    echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee...${COLOR_DEFAULT}"
                                    read -p "[*] Do you want to install fox file by default installation plan ? (y/N)" answer
                                    case $answer in
                                        [Yy]) get_from_github;;
                                        *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                                    esac
                                fi
                            else
                                echo -e "${COLOR_RED}[-] FOX file is lost! It seems that the $package is no supported get from gitee or need expand...${COLOR_DEFAULT}"
                                read -p "[*] Do you want to try for install fox file by default installation plan ? (y/N)" answer
                                case $answer in
                                    [Yy]) get_from_github;;
                                    *) echo -e "${COLOR_RED}[-] Exit...${COLOR_DEFAULT}" && exit 1;;
                                esac
                            fi
                        fi
                    else
                        get_from_github
                    fi
                fi
                get_run "upgrade"
                update_run
                run="${run//\$MAIN_DIR/$MAIN_DIR}"
                run="${run//\$BIN/$BIN}"
                run="${run//\$PACKAGE_INSTALL/$PACKAGE_INSTALL}"
                run="${run//\$PACKAGE_UPGRADE/$PACKAGE_UPGRADE}"
                run="${run//\$PACKAGE_REMOVE/$PACKAGE_REMOVE}"
                if [ "$parameters_1" = "--debug" ] || [ "$package" = "--debug" ]; then
                    echo -e "${COLOR_BLUE}[*] $run${COLOR_DEFAULT}"
                fi
                eval "$run"
                echo -e "${COLOR_GREEN}[+] Package '$package' upgraded.${COLOR_DEFAULT}"
                update_now_version
            else
                echo -e "${COLOR_YELLOW}[*] Package '$package' already the latest version.${COLOR_DEFAULT}"
                continue
            fi
        done
    else
        echo -e "${COLOR_YELLOW}[*] No packages are currently installed.${COLOR_DEFAULT}"
    fi
}

update_now_version() {
    sed -i "s/^$package:$now_version$/$package:$latest_version/" "$INED"
}

update() {
    curl -o "$FOXINDEX/FOXINDEX.tar.gz" -L "$source_url/FOXINDEX.tar.gz"
    if [ $? -ne 0 ]; then
        echo -e "${COLOR_RED}[-] Failed to download FOXINDEX.tar.gz. Check your software source.${COLOR_DEFAULT}"
        exit 1
    fi
    tar -xf "$FOXINDEX/FOXINDEX.tar.gz" -C "$FOXINDEX/"
    rm "$FOXINDEX/FOXINDEX.tar.gz"
    generate_package_info
    echo -e "${COLOR_GREEN}[+] Package index has been updated.${COLOR_DEFAULT}"
}

info() {
    if [ -s "$FOXINDEX/FOXINDEX" ]; then
        if grep -q "^P:$package$" "$FOXINDEX/FOXINDEX"; then
            grep -A 5 "^P:$package$" "$FOXINDEX/FOXINDEX" | awk 'BEGIN{pkg="";ver="";lang="";status="";info="";github=""} 
                /^P:/{pkg=$0}
                /^V:/{ver=$0}
                /^L:/{lang=$0}
                /^S:/{status=$0}
                /^T:/{info=$0}
                /^G:/{github=$0}
                END{
                    printf "Package: \033[32m%s\033[0m\n", substr(pkg, 3); 
                    printf "Version: \033[32m%s\033[0m\n", (ver=="" ? "Not available" : substr(ver, 3));
                    printf "Language: \033[32m%s\033[0m\n", (lang=="" ? "Not available" : substr(lang, 3));
                    printf "Maintenance Status: \033[32m%s\033[0m\n", (status=="" ? "Not available" : substr(status, 3));
                    printf "Introduction: \033[32m%s\033[0m\n", (info=="" ? "Not available" : substr(info, 3));
                    printf "GitHub: \033[32m%s\033[0m\n", (github=="" ? "Not available" : substr(github, 3))
            }'
        else
            echo -e "${COLOR_RED}[-] Package $package not found. Please check if the package name is correct.${COLOR_DEFAULT}"
        fi
    else
        echo -e "${COLOR_RED}[-] FOXINDEX file loss. Try \"fox update\"${COLOR_DEFAULT}"
    fi
}

get_ver() {
    if [ -s "$FOXINDEX/FOXINDEX" ]; then
        package_info=$(grep -A 5 "^P:$package$" "$FOXINDEX/FOXINDEX")
        version=$(echo "$package_info" | grep "^V:" | awk -F: '{print $2}' | tr -d '[:space:]')
    else
        echo -e "${COLOR_RED}[-] FOXINDEX file loss. Try \"fox update\"${COLOR_DEFAULT}"
    fi
}

#ABOUT部分函数
about() {
    echo ""
    echo -e "${COLOR_BLUE}[Gitee Project Main Address]${COLOR_DEFAULT}"
    echo -e "${COLOR_CYAN} > https://gitee.com/TangYuanMaster/JiuWei${COLOR_DEFAULT}"
    echo ""
    echo -e "${COLOR_BLUE}[Gitee Project Repository Address]${COLOR_DEFAULT}"
    echo -e "${COLOR_CYAN} > https://gitee.com/TangYuanMaster/JiuWei-repository${COLOR_DEFAULT}"
    echo ""
    echo -e "${COLOR_BLUE}[Maintor&Developer]${COLOR_DEFAULT}"
    echo -e "${COLOR_CYAN} > TangYuanMaster${COLOR_DEFAULT}"
}

main() {
    logo
    case "$command" in
        install)
            if [[ -z $package ]]; then
                echo -e "${COLOR_YELLOW}[*] No package specified.${COLOR_DEFAULT}"
                exit 1
            else
                check_code
                install_package
            fi
            ;;
        remove)
            if [[ -z $package ]]; then
                echo -e "${COLOR_YELLOW}[*] No package specified.${COLOR_DEFAULT}"
                exit 1
            else
                check_code
                remove_package
            fi
            ;;
        list)
            if [[ -n $package ]]; then
                echo -e "${COLOR_YELLOW}[*] Package parameter is not required for 'list' command.${COLOR_DEFAULT}"
            fi
            list_packages
            ;;
        search)
            if [[ -z $package ]]; then
                echo -e "${COLOR_YELLOW}[*] No package specified.${COLOR_DEFAULT}"
                exit 1
            else
                check_code
                search_package
            fi
            ;;
        upgrade)
            check_code
            if [[ -z $package ]]; then
                upgrade_all_packages
            else
                upgrade_a_package
            fi
            ;;
        update)
            if [[ -n $package ]]; then
                echo -e "${COLOR_YELLOW}[*] Package parameter is not required for 'update' command.${COLOR_DEFAULT}"
            fi
            update
            ;;
        info)
            if [[ -z $package ]]; then
                echo -e "${COLOR_YELLOW}[*] No package specified.${COLOR_DEFAULT}"
                exit 1
            else
                info
            fi
            ;;
        ABOUT)
            if [[ -n $package ]]; then
                echo -e "${COLOR_YELLOW}[*] Package parameter is not required for 'update' command.${COLOR_DEFAULT}"
            fi
            about
            ;;
        *)
            echo -e "${COLOR_YELLOW}[*] Unknown command: $command.${COLOR_DEFAULT}"
            usage
            ;;
    esac
}

sys_info=$(uname -a)
if [ -f "/etc/os-release" ]; then
    if grep -qi 'ID=*alpine*' /etc/os-release; then
        sys_name="alpine"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="apk add"
        PACKAGE_UPGRADE="apk upgrade"
        PACKAGE_REMOVE="apk del"
    elif grep -qi 'ID=*debian*' /etc/os-release; then
        sys_name="debian"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="apt install -y"
        PACKAGE_UPGRADE="apt install --only-upgrade"
        PACKAGE_REMOVE="apt remove"
    elif grep -qi 'ID=*ubuntu*' /etc/os-release; then
        sys_name="ubuntu"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="apt install -y"
        PACKAGE_UPGRADE="apt install --only-upgrade"
        PACKAGE_REMOVE="apt remove"
    elif grep -qi 'ID=*kali*' /etc/os-release; then
        sys_name="kali"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="apt install -y"
        PACKAGE_UPGRADE="apt install --only-upgrade"
        PACKAGE_REMOVE="apt remove"
    elif grep -qi 'ID=*arch*' /etc/os-release; then
        sys_name="arch"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="pacman -S"
        PACKAGE_UPGRADE="pacman -Su"
        PACKAGE_REMOVE="pacman -Rns"
    elif grep -qi 'ID=*centos*' /etc/os-release; then
        sys_name="centos"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="yum install -y"
        PACKAGE_UPGRADE="yum update"
        PACKAGE_REMOVE="yum remove"
    elif grep -qi 'ID=*rhel*' /etc/os-release; then
        sys_name="redhat"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="yum install -y"
        PACKAGE_UPGRADE="yum update"
        PACKAGE_REMOVE="yum remove"
    fi
else
    if [ -n "$TERMUX_VERSION" ]; then
        sys_name="termux"
        SYSTEM_CATEGORY="linux"
        PACKAGE_INSTALL="pkg install -y"
        PACKAGE_UPGRADE="pkg upgrade -y"
        PACKAGE_REMOVE="pkg uninstall -y"
    elif command -v "sw_vers"; then
        sys_name="darwin"
        SYSTEM_CATEGORY="darwin"
        PACKAGE_INSTALL="brew install -y"
        PACKAGE_UPGRADE="brew upgrade -y"
        PACKAGE_REMOVE="brew uninstall"
    fi
fi
if [[ ! -n "$sys_name" ]]; then
    echo -e "${COLOR_RED}[-] Current system is not supported. ${COLOR_DEFAULT}"
    exit 1
fi

sys_arch=$(uname -m)
if [[ $sys_arch == x86_64 ]]; then
    sys_arch="amd64"
elif [[ $sys_arch == aarch64 ]]; then
    sys_arch="arm64"
elif [[ $sys_arch == i*86 ]]; then
    sys_arch="386"
fi

update_run() {
    if [ "$parameters_1" = "--no-update" ] || [ "$parameters_2" = "--no-update" ]; then
        echo -e "${COLOR_YELLOW}[*] Skip update～=_=${COLOR_DEFAULT}"
    else
        echo -e "${COLOR_YELLOW}[*] Update...${COLOR_DEFAULT}"
        if [ "$sys_name" = "alpine" ]; then
            local run="apk update"
        elif [ "$sys_name" = "debian" ] || [ "$sys_name" = "ubuntu" ] || [ "$sys_name" = "kali" ]; then
            local run="apt update"
        elif [ "$sys_name" = "arch" ]; then
            local run="pacman -Sy"
        elif [ "$sys_name" = "centos" ] || [ "$sys_name" = "redhat" ]; then
            local run="dnf -y update"
        elif [ "$sys_name" = "termux" ]; then
            local run="apt update"
        elif [ "$sys_name" = "darwin" ]; then
            local run="brew update"
        fi
    fi
    if [ "$parameters_1" = "--debug" ] || [ "$parameters_2" = "--debug" ]; then
        echo -e "${COLOR_BLUE}[*] $run${COLOR_DEFAULT}"
    fi
    eval "$run"
}

#基础命令环境检测
check_code() {
    echo -e "${COLOR_GREEN}[+] Check the software package dependence...Wait.${COLOR_DEFAULT}"
    if [ -f "$ST" ]; then
        for cmd in wget curl git perl rust cargo perl python2 pip2 java node npm; do
            if ! command -v $cmd; then
                echo -e "${COLOR_RED}[!] $cmd command not found. Re-executing Setup_JiuWei try. ${COLOR_DEFAULT}"
            fi
        done
    else
        for cmd in wget curl git python3 pip3 ruby gem bc go; do
            if ! command -v $cmd; then
                echo -e "${COLOR_RED}[!] $cmd command not found. Re-executing Expand_JiuWei try. ${COLOR_DEFAULT}"
            fi
        done
    fi
}
command=$1
package=$2
parameters_1=$3
parameters_2=$4
if [[ "$package" == "--"* ]]; then
    echo -e "${COLOR_RED}[!] The package name is incorrect, please detect if the parameter is correct. ${COLOR_DEFAULT}"
    exit 1
fi

main "$@"